export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);

    const echartsScriptTag = document.createElement('script');
    echartsScriptTag.src = 'https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js';
    document.head.appendChild(echartsScriptTag);

    const self = this;

    const ddcatSources = [
        { id: "", name: "专项检查实施方案-方案统计分析" },
        { id: "ds_mod:763b1b5d-120b-4c58-9b65-bd5ae9ba9d66", name: "专项检查实施方案-联合情况" }
    ];

    // 联合情况
    fetchDdcatData(ddcatSources[1].id).then(res => {
        if (res && res.length) {
            loadJointInfoPieChart(self, res);
        } else {
            const mockData = getRandomNum();
            loadJointInfoPieChart(self, mockData);
        }
    });


}



/**
 * 加载联合情况环形图
 */
function loadJointInfoPieChart(self, data) {

    const chartContainer = self.$$("text_5q5gj1").$el;
    const myChart = echarts.init(chartContainer);

    const total = data.reduce((sum, item) => sum + Number(item.unionData), 0);

    // 渐变色配置
    const gradientColors = [
        { start: '#85C0FF', end: '#3388FF' }, // 主动联合
        { start: '#FFD152', end: '#FFAA00' }  // 推荐联合
    ];
    const createGradient = (index) => {
        const gradient = gradientColors[index % gradientColors.length];
        return new echarts.graphic.LinearGradient(0, 0, 1, 1, [
            { offset: 0, color: gradient.start },
            { offset: 1, color: gradient.end }
        ]);
    };

    const option = {
        legend: {
            orient: 'horizontal',
            left: '35%',
            top: 'middle',
            itemWidth: 10,
            itemHeight: 10,
            itemGap: 30,
            formatter: (name) => {
                const item = data.find(d => d.jointType === name);
                const percent = total === 0 ? 0 : ((Number(item.unionData) / total) * 100).toFixed(0);
                return `{name|${name}}{value|${item.unionData}}{space| }{percentage|${percent}%}`;
            },
            textStyle: {
                rich: {
                    name: { width: 70, align: 'left' },
                    value: { width: 40, align: 'right' },
                    percent: { width: 40, align: 'right' }
                }
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        series: [
            {
                type: 'pie',
                radius: ['65%', '85%'],
                center: ['15%', '50%'],
                label: { show: false },
                emphasis: { label: { show: false } },
                data: data.map((item, index) => ({
                    name: item.jointType,
                    value: Number(item.unionData),
                    itemStyle: {
                        color: createGradient(index)
                    }
                }))
            }
        ],
        graphic: {
            type: 'text',
            left: '10.5%',
            top: '35%',
            style: {
                text: `{total|${total}}\n{label|制定总数}`,
                textAlign: 'center',
                rich: {
                    total: {
                        fontSize: 24,
                        fontWeight: 500,
                        color: '#223355',
                        lineHeight: 24
                    },
                    label: {
                        fontSize: 14,
                        fontWeight: 400,
                        color: '#223355',
                        lineHeight: 24
                    }
                }
            }
        }
    };

    myChart.setOption(option);
}

/**
 * 从 ddcat 数据源拉取所有数据
 * @returns Promise<数组> - 返回结果数组
 */
function fetchDdcatData(sourceId) {
    const jsonParams = { pageSize: 99999 };
    return api.DATA_SOURCE_EXECUTE(
        sourceId,
        "ddcat",
        [],
        [],
        JSON.stringify(jsonParams)
    ).then(res => {

        if (res && !res.hasError && res.result != null) {
            return res.result;
        } else {
            console.warn("查询失败或数据为空，生成模拟数据");
            // 这里生成模拟数据
            return [];
        }
    });
}


/**
 * 联合情况
 */
function getRandomNum() {
    const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

    return [
        { jointType: '主动联合', unionData: randomBetween(1000, 5000) },
        { jointType: '推荐联合', unionData: randomBetween(1000, 5000) }
    ];
}
